package com.nlelpct.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nlelpct.manage.constant.ResponseCode;
import com.nlelpct.manage.constant.SystemConstant;
import com.nlelpct.manage.context.ThreadParameter;
import com.nlelpct.manage.mapper.SysCompanyBasicInfoMapper;
import com.nlelpct.manage.mapper.SysCompanyMapper;
import com.nlelpct.manage.mapper.SysEmployeeMapper;
import com.nlelpct.manage.mapper.UserMapper;
import com.nlelpct.manage.model.entity.SysCompany;
import com.nlelpct.manage.model.entity.SysCompanyBasicInfo;
import com.nlelpct.manage.model.entity.SysEmployee;
import com.nlelpct.manage.model.entity.User;
import com.nlelpct.manage.model.query.UserChangePasswordQuery;
import com.nlelpct.manage.model.security.MyUser;
import com.nlelpct.manage.model.vo.EmployeeAndCompanyInfoVo;
import com.nlelpct.manage.model.vo.ResponseResult;
import com.nlelpct.manage.service.IOssService;
import com.nlelpct.manage.service.IUserService;
import com.nlelpct.manage.utils.LoginPasswordEncoderUtils;
import com.nlelpct.manage.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.ObjectUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author :小马
 * @date : 2023-07-21
 */
@Service
public class UserServiceImpl implements IUserService {

    private final SysEmployeeMapper sysEmployeeMapper;

    private final SysCompanyMapper sysCompanyMapper;

    private final SysCompanyBasicInfoMapper sysCompanyBasicInfoMapper;

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(SysEmployeeMapper sysEmployeeMapper, SysCompanyMapper sysCompanyMapper, SysCompanyBasicInfoMapper sysCompanyBasicInfoMapper, UserMapper userMapper) {
        this.sysEmployeeMapper = sysEmployeeMapper;
        this.sysCompanyMapper = sysCompanyMapper;
        this.sysCompanyBasicInfoMapper = sysCompanyBasicInfoMapper;
        this.userMapper = userMapper;
    }

    @Override
    public ResponseResult<List<EmployeeAndCompanyInfoVo>> listCompany() {
        String systemId = ThreadParameter.getLocalMap().get(SystemConstant.SYSTEM_ID);
        // 1. 获取userID
        String userId = ((MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
        // 2. 获取员工List
        LambdaQueryWrapper<SysEmployee> employeeQueryWrapper = new LambdaQueryWrapper<>();
        employeeQueryWrapper.eq(SysEmployee::getUserId, userId)
                .eq(SysEmployee::getSystemId, systemId);
        List<SysEmployee> employeeList = sysEmployeeMapper.selectList(employeeQueryWrapper);
        if (ObjectUtil.isEmpty(employeeList)) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "当前用户尚未加入任何企业！");
        }
        // 3. 找出所有的CompanyId
        List<String> companyIds = employeeList.stream()
                .map(SysEmployee::getCompanyId).collect(Collectors.toList());
        Map<String, SysEmployee> employeeUserNameMap = employeeList.stream()
                .collect(Collectors.toMap(SysEmployee::getCompanyId, ele -> ele, (a, b) -> b));
        // 4. 通过CompanyIds 组装company数据
        List<SysCompany> companies = sysCompanyMapper.selectBatchIds(companyIds);
        Map<String, SysCompany> companyMap = companies.stream()
                .collect(Collectors.toMap(SysCompany::getCompanyBasicId, com -> com, (a, b) -> b));
        List<String> companyBasicInfoIds = companies.stream().map(SysCompany::getCompanyBasicId).collect(Collectors.toList());
        List<SysCompanyBasicInfo> companyBasicInfos = sysCompanyBasicInfoMapper.selectBatchIds(companyBasicInfoIds);
        // 5. 组装企业id 名字 logo 状态 license  员工名字
        ArrayList<EmployeeAndCompanyInfoVo> resultList = new ArrayList<>(companyBasicInfos.size());
        String companyId;
        SysCompany sysCompany;
        for (SysCompanyBasicInfo companyBasicInfo : companyBasicInfos) {
            sysCompany = companyMap.get(companyBasicInfo.getCompanyBasicId());
            companyId = sysCompany.getCompanyId();
            EmployeeAndCompanyInfoVo tmpVo = new EmployeeAndCompanyInfoVo();
            tmpVo.setLisenceExpire(sysCompany.getLisenceExpire());
            tmpVo.setEmployeeId(employeeUserNameMap.get(companyId).getEmployeeId());
            tmpVo.setEmployeeStatus(employeeUserNameMap.get(companyId).getEmployeeStatus());
            tmpVo.setCompanyId(companyId);
            tmpVo.setCompanyStatus(sysCompany.getCompanyStatus());
            tmpVo.setCompanyLogo(IOssService.composeImageUrl(companyBasicInfo.getCompanyLogo()));
            tmpVo.setCompanyZhName(companyBasicInfo.getCompanyZhName());
            tmpVo.setCompanyEnName(companyBasicInfo.getCompanyEnName());
            resultList.add(tmpVo);
        }
        return ResponseResult.success(resultList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<String> changeUserPassword(UserChangePasswordQuery changePasswordQuery) {
        MyUser myUser;
        try {
            myUser = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (ClassCastException e) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, changePasswordQuery.getPhoneNumber());
            queryWrapper.select(User::getId, User::getPhone, User::getPassword, User::getZt);
            User user = userMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(user)) {
                return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "该账号在系统中不存在!");
            }
            if (!SystemConstant.USER_STATUS_NORMAL.equals(user.getZt())) {
                return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "该用户已被禁用或删除,请联系系统管理员!");
            }
            myUser = new MyUser();
            myUser.setUserId(user.getId());
            myUser.setUsername(user.getPhone());
            myUser.setPassword(LoginPasswordEncoderUtils.encode(user.getPassword()));
        }

        if (!LoginPasswordEncoderUtils.matches(MD5Utils.getMD5String(changePasswordQuery.getOldPassword()), myUser.getPassword())) {
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "旧密码输入错误");
        }
        User user = new User();
        user.setId(myUser.getUserId());
        user.setPassword(MD5Utils.getMD5String(changePasswordQuery.getNewPassword()));
        user.setLastResetPasswd(LocalDateTime.now());
        user.setXgsj(LocalDateTime.now());
        user.updateById();
        return ResponseResult.success("修改密码成功");
    }
}
